# -*- coding: utf-8 -*-
# Create your views here.

from django.http import HttpResponse        # 导入HttpResponse类


# version 1
# def hello(request):                         # requset是请求信息，HttpRequest类
#    return HttpResponse('Hello World')      # http返回

# version 2
# def hello(request):
#    name = request.GET.get('name', 'World')     # 获得参数
#    return HttpResponse('Hello ' + name)

# version 3
def hello(request, name='World'):               # name用来接收新参数
   return HttpResponse('Hello ' + name)


from models import *
import json
from datetime import datetime


# 查询

def query_all(request):
    # 获得所有数据
    students = Students.objects.all()
    data = [i.name for i in students]
    return HttpResponse(json.dumps(data, ensure_ascii=False))


def query_get(request, name):
    # 查询一个
    try:
        student = Students.objects.get(name=name)
        return HttpResponse(student.name)
    except Exception, e:
        return HttpResponse('不存在')


def query_filter(request, name, cls):
    # 条件查询
    # 方法一
    # c = Class.objects.get(name__contains=cls)
    # students = Students.objects.filter(name__contains=name, cls=c)

    # 方法二
    students = Students.objects.filter(name__contains=name, cls__name__contains=cls)

    if len(students) == 0:
        return HttpResponse('不存在')
    else:
        data = [i.name for i in students]
        return HttpResponse(json.dumps(data, ensure_ascii=False))


def add_student(request, name, cls):
    cls = Class.objects.get(name__contains=cls)



    # 方法一
    student = Students(name=name, free=True, score=1,
                       sex=1, type=1, birthday=datetime.now(),
                       description='a', remark='a', cls=cls)

    student.subject.add(Subject.objects.all())
    # student.subject.remove()

    student.save()



    # 方法二
    # student = Students.objects.create(name=name, free=True, score=1,
    #                         sex=1, type=1, birthday=datetime.now(),
    #                         description='a', remark='a', cls=cls)

    return HttpResponse('ok')


def update_student(request, name, remark):

    # 方法一
    Students.objects.filter(name__contains=name).update(remark=remark, free=True)

    # 方法二
    # student = Students.objects.get(name__contains=name)
    # student.remark = remark
    # student.save()

    return HttpResponse('ok')


def delete_student(request, name):

    Students.objects.filter(name__exact=name).delete()
    return HttpResponse('ok')